// Copyright (C) 2024 wlly-lzh
// Created by wlly-lzh on 24-4-6
// 用于公共调用的队列
#ifndef _LINKEDQUEUE_C
#define _LINKEDQUEUE_C

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "linkedlist.c"

typedef struct LinkedQueue LinkedQueue;
struct LinkedQueue {
	LinkedList *Head;
	LinkedList *Tail;
	LinkedList *Store;
	unsigned int Size;
};

LinkedQueue *Create_LinkedQueue(){
	LinkedQueue *newQueue;
	newQueue=(LinkedQueue *)malloc(sizeof(LinkedQueue));
	if(newQueue == NULL){
		printf("liblds: Malloc False!\n");
		exit(3);
	}
	newQueue->Head=newQueue->Tail=NULL;
	newQueue->Store=NULL;
	newQueue->Size=0;
	return newQueue;
}
void Destroy_LinkedQueue(LinkedQueue **Queue){
	if((*Queue)->Head != NULL)
		Clear_LinkedList((*Queue)->Head);
	if((*Queue)->Store != NULL)
		Clear_LinkedList((*Queue)->Store);
	free(*Queue);
	*Queue=NULL;
}
// 1 2 3 4 5
// 5 2 6
void En_LinkedQueue(LinkedQueue *Queue,void *Data){
	LinkedList * newList;
	if(Queue->Store != NULL){
		newList=Queue->Store;
		newList->Data=Data;
		Queue->Store=newList->Next;
		newList->Next=NULL;
		if(Queue->Size > 0){
			Queue->Tail->Next=newList;
		}else{
			Queue->Head=newList;
		}
		Queue->Tail=newList;
	}else{
		newList=(LinkedList *)malloc(sizeof(LinkedList));
		if(newList == NULL){
			printf("liblds: Malloc False!\n");
			exit(3);
		}
		newList->Data=Data;
		newList->Next=NULL;
		if(Queue->Size > 0){
			Queue->Tail->Next=newList;
		}else{
			Queue->Head=newList;
		}
		Queue->Tail=newList;
	}
	Queue->Size++;
}
void De_LinkedQueue(LinkedQueue *Queue,void **Data){
	LinkedList *Del=Queue->Head;
	if(Queue->Size > 0){
		*Data=Del->Data;
		Queue->Head=Del->Next;
		Queue->Size--;
		//free(Del);
		Del->Next=Queue->Store;
		Queue->Store=Del;
	}else{
		*Data=NULL;
	}
}
bool IsEmpty_LinkedQueue(const LinkedQueue *Queue){
	if(Queue->Size == 0)
		return true;
	else
		return false;
}
unsigned int Length_LinkedQueue(const LinkedQueue *Queue){
	return Queue->Size;
}
#endif // _LINKEDQUEUE_C
